package com.blac.ad

import android.app.Activity
import android.content.Context
import android.util.Log
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxError
import com.applovin.mediation.MaxReward
import com.applovin.mediation.MaxRewardedAdListener
import com.applovin.mediation.ads.MaxRewardedAd
import com.blac.Constant
import com.blac.utils.ADManager

object MaxReward {
    private var maxRewardedAd: MaxRewardedAd?=null
    private var adSource : String =""

    fun loadRewardAd(context :Context){
        maxRewardedAd = MaxRewardedAd.getInstance(Constant.REWARD_PLACEMENTID, context)
        setListener()
        loadRewardAd()
    }

    private fun loadRewardAd(){
        maxRewardedAd?.loadAd()
    }

    private fun setListener(){
        maxRewardedAd?.setListener(AdListener())
    }

    fun isReady():Boolean{
        return maxRewardedAd?.isReady==true
    }

    fun showAd(activity: Activity, adSource:String){
        if (adSource.isNotEmpty()){
            this.adSource = adSource
        }
        getRewardAd(activity)
        setListener()
        show()
    }

    private fun show(){
        if (isReady()){
            maxRewardedAd?.showAd()
        }else{
            ADManager.callbackAdError()
            loadRewardAd()
        }
    }

    private fun getRewardAd(activity:Activity){
        if (maxRewardedAd == null){
            maxRewardedAd = MaxRewardedAd.getInstance(Constant.REWARD_PLACEMENTID,activity)
        }

    }

    private class AdListener :MaxRewardedAdListener{
        override fun onAdLoaded(p0: MaxAd) {
            Log.e("xsd","onAdLoaded")
        }

        override fun onAdDisplayed(p0: MaxAd) {

        }

        override fun onAdHidden(p0: MaxAd) {
            loadRewardAd()
            ADManager.callbackAdOver(adSource)
        }

        override fun onAdClicked(p0: MaxAd) {

        }

        override fun onAdLoadFailed(p0: String, p1: MaxError) {

        }

        override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
            ADManager.callbackAdError()
        }

        override fun onUserRewarded(p0: MaxAd, p1: MaxReward) {

        }

    }
}